package com.pinyougou.shop.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {
    @PostMapping("/login")
    public String login(String username,String password){
        //用shiro来做身份认证

        try {
            //获取主体
            Subject subject = SecurityUtils.getSubject();
            //创建用户令牌
            UsernamePasswordToken token =new UsernamePasswordToken(username,password);
            //身份验证
            subject.login(token);

            if (subject.isAuthenticated()){
                return "redirect:/admin/index.html";
            }
        } catch (AuthenticationException e) {
            e.printStackTrace();
        }
        return "redirect:/shoplogin.html";
    }
    @GetMapping("/findLoginName")
    @ResponseBody
    public Map<String ,String>findLoginName(){
        String loginName = SecurityUtils.getSubject()
                .getPrincipal().toString();
        Map<String,String> data = new HashMap<>();
        data.put("loginName", loginName);
        return data;
    }
}
